<?php
namespace app\index\controller;

use app\common\model\ArticleCate;
use think\Request;
use app\common\model\Article as ArticleModel;
use app\common\model\ArticleCate as ArticleCateModel;


class Article extends Base{

    /**
     * 分类的封面
     * @param Request $request
     * @return \think\response\View
     */
    public function index(Request $request){
        $cate_id = $request->param('id',0);
        if(empty($cate_id)) $cate_id = 1;
        $cate = ArticleCateModel::get($cate_id);
        if(!$cate){
            $this->error('内容不存在');
        }

        //获取模板
        //var_dump(get_defined_constants());exit;
        //return $this->fetch($this->template_root.'ceshi.html',$this->data);
        $this->data['cate_id'] = $cate_id;
        return $this->fetch($this->template_root.$cate['index_template'],$this->data);
    }


    /**
     * 分类的列表
     * @param Request $request
     * @return \think\response\View
     */
    public function lists(Request $request){
        $cate_id = $request->param('id',0);
        if(empty($cate_id)) $cate_id = 1;
        $cate = ArticleCateModel::get($cate_id);
        if(!$cate){
            $this->error('内容不存在');
        }
        $this->data['cate_id'] = $cate_id;
        return $this->fetch($this->template_root.$cate['lists_template'],$this->data);
    }

    /**
     * 分类的文章详情
     * @return \think\response\View
     */
    public function detail(Request $request){
        $id = $request->param('id');
        $model = ArticleModel::get($id);


        $model->content = str_replace("http://www.daogou123.cn","http://www.yuanbaohua.top",$model->content);
        $model->content = str_replace("\r\n","<br />",$model->content);

        //上下一篇
        $prev = ArticleModel::where(['add_time'=>['<',$model->add_time]])->order('add_time desc')->find();
        $next = ArticleModel::where(['add_time'=>['>',$model->add_time]])->order('add_time asc')->find();

        $this->data['model'] = $model;
        $this->data['prev'] = $prev;
        $this->data['next'] = $next;

        $model->pv++;
        $model->save();

        return $this->fetch($this->template_root.'content_template.html',$this->data);
    }

    /**
     *
     * @param Request $request
     */
    public function search(Request $request){
        $keyword = $request->get('keyword');
        if(empty($keyword)){
            $this->error("请输入搜索关键词");
        }
        $articles  = ArticleModel::where(['title'=>['like','%'.$keyword.'%']])->paginate(10,false,['query'=>['keyword'=>$keyword]]);

        $this->data['model'] = $articles;
        $this->data['keyword'] = $keyword;
        return view($this->template_root.'search_template.html',$this->data);
    }

}